package com.higgins.client.agentapp.settingstabs;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.higgins.client.GreetingService;
import com.higgins.client.GreetingServiceAsync;
import com.higgins.client.agentapp.components.AgentColumns;
import com.higgins.client.agentapp.components.AgentTable;
import com.higgins.client.agentapp.components.JobSiteColumns;
import com.higgins.client.agentapp.components.JobSiteTable;
import com.higgins.client.agentapp.datamodel.AgencyDTO;
import com.higgins.client.agentapp.service.AgentAppService;
import com.higgins.client.agentapp.service.AgentAppServiceAsync;

public class AgentTab extends VerticalPanel {
	private final AgentAppServiceAsync agentAppService = GWT
		.create(AgentAppService.class);
	private AgentTable agentTable;
	private ListBox agencyList = new ListBox();
	private List<AgencyDTO> agencyDTOList;
	private boolean firstRun = true;
	public AgentTab()	{
	}
	public void update()	{
		if (firstRun)
			initialise();
		else
			refresh();
	}
	
	public void initialise()	{
		firstRun = false;
		generateAgencyList();
	}
	public void refresh()	{
		
	}
	public void generateAgencyList()	{
		agentAppService.retrieveAgencys(new AsyncCallback<List<AgencyDTO>>()  {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<AgencyDTO> result) {
				agencyDTOList = result;
				for (AgencyDTO agencyDTO:agencyDTOList)	{
					agencyList.addItem(agencyDTO.getName());
				}
				agencyList.setItemSelected(0, true);
				add(agencyList);
				updateTable();
				agencyList.addChangeHandler(new ChangeHandler()  {
					@Override
					public void onChange(ChangeEvent event) {
						updateTable();
					}
				});
			}
			
		});
	}
	public void updateTable()	{
		if (agentTable!=null)
			remove(agentTable);
		AgencyDTO selectedAgencyDTO = getSelectedAgencyDTO();
		AgentColumns agentColumns = new AgentColumns();
		agentTable = new AgentTable(agentColumns);
		agentTable.update(selectedAgencyDTO);
		add(agentTable);
	}
	public AgencyDTO getSelectedAgencyDTO()	{
		int selectedIndex = agencyList.getSelectedIndex();
		AgencyDTO selectedAgencyDTO = agencyDTOList.get(selectedIndex);
		return selectedAgencyDTO;
	}
}
